import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
# Create your views here.
from book_drf.serializers import BooksSerialzier
from book_drf.serializers import HeroSerialzier
from books.models import BookInfo
from books.models import HeroInfo


class BooksDRF(View):
    """
        获取所有图书和保存图书
    """

    def get(self, requst):
        # 1、查询所有图书s
        books = BookInfo.objects.all()
        # Heros  = HeroInfo.objects.all()

        # 2、返回图书数据
        ser = BooksSerialzier(books, many=True) # [[],[],,,,]
        # ser = HeroSerialzier(Heros, many=True)
        print(ser.data)
        return JsonResponse(ser.data, safe=False)  #序列化器的对象调data 方法，data方法提取了instance 属性中字段信息,data就是return
        #的是序列化的的结果，通过序列化的对象调用[{}，{}，{}，{}，，，，]

    def post(self, request):
        # 1、获取前端数据
        data = request.body.decode()
        data_dict = json.loads(data)
        print(data_dict)

        # 2、验证数据
        ser = BooksSerialzier(data=data_dict)
        # ser = HeroSerialzier(data=data_dict)
        ser.is_valid(raise_exception=True)
        #raise_exception=True在实际开发中如果验证出现错误后面的代码不会执行，
        # ser.is_valid()
        # print(ser.validated_data)
        # # 3、保存数据
        ser.save()
        # # 4、返回结果
        # print(ser.data)
        # return JsonResponse(ser.errors)
        return JsonResponse(ser.data)


class BookDRF(View):
    """
        获取单一图书和修改删除
    """

    def get(self, requst, pk):
        # 1、查询数据
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '数据错误'}, status=400)
        # 返回数据
        return JsonResponse(
            {
                'id': book.id,
                'btitle': book.btitle,
                'bread': book.bread,
                'bpub_date': book.bpub_date,
            }
        )

    def put(self, request, pk):
        # 1、获取前端数据
        data = request.body.decode()
        data_dict = json.loads(data)
        # 2、验证数据
        # 查询数据
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '数据错误'}, status=400)
        ser = BooksSerialzier(book, data=data_dict)
        ser.is_valid(raise_exception=True)
        # 3、更新数据
        ser.save()
        # 4、返回结果
        return JsonResponse(
            ser.data)

    def delete(self, request, pk):
        # 1、查询数据
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '数据错误'}, status=400)

        book.is_delete = True
        book.save()
        return JsonResponse({})
